using System;
using System.Data;
using System.Data.SqlClient;
using SqlSugar;

namespace SqlSugarEx.Realization
{
	public class SqlServerProviderEx : SqlServerProvider
	{
		private System.Data.SqlClient.SqlDataAdapter _sqlAdp;

		private DataSet _dsBind;

		public Func<SqlRowUpdatingEventArgs, string> RowUpdatingHandler { get; set; }

		public override DataTable GetDataTable(string sql, params SugarParameter[] parameters)
		{
			SqlConnection sqlConnection = new SqlConnection
			{
				ConnectionString = this.Connection.ConnectionString
			};
			try
			{
				SqlSugar.IDataAdapter adapter = this.GetAdapter();
				if (adapter is SqlSugar.SqlDataAdapter)
				{
					SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
					foreach (SugarParameter sugarParameter in parameters)
					{
						sqlCommand.Parameters.Add(new SqlParameter(sugarParameter.ParameterName, sugarParameter.Value));
					}
					this._sqlAdp = new System.Data.SqlClient.SqlDataAdapter(sqlCommand);
					this._sqlAdp.MissingSchemaAction = MissingSchemaAction.AddWithKey;
					SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(this._sqlAdp);
					this._dsBind = new DataSet();
					this._sqlAdp.Fill(this._dsBind);
					return this._dsBind.Tables[0];
				}
				return new DataTable();
			}
			catch (Exception ex)
			{
				throw ex;
			}
			finally
			{
				if (this.Context.CurrentConnectionConfig.IsAutoCloseConnection)
				{
					sqlConnection.Close();
				}
			}
		}

		public bool UpdateBind()
		{
			try
			{
				this._sqlAdp.Update(this._dsBind);
				this._sqlAdp.Fill(this._dsBind);
				this._dsBind.AcceptChanges();
				return true;
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}
	}
}
